var CONSTANTS = {
        FLOW_STATUS: {
            "FINISHED": {"label-class": "label-primary", "label-text": "已结束"},
            "UNFINISHED": {"label-class": "label-info", "label-text": "未结束"},
            "SUSPENDED": {"label-class": "label-default", "label-text": "挂起"}
        }
    }
;var global = (function ($, window) {
    var NO_DATA_HTML = "<div class=\"container-fluid\"><div class=\"ibox \"><div class=\"ibox-content text-center\"><h2><i class=\"glyphicon glyphicon-info-sign\"></i>{{message}}</h2></div></div></div>";
    var LOADING_HTML = "<div class=\"container-fluid\"><div class=\"ibox \"><div class=\"ibox-content\"><div class=\"spiner-example\"><div class=\"sk-spinner sk-spinner-wave\"><div class=\"sk-rect1\"></div><div class=\"sk-rect2\"></div><div class=\"sk-rect3\"></div><div class=\"sk-rect4\"></div><div class=\"sk-rect5\"></div></div></div></div></div></div>";
    var ERROR_DATA_HTML = "<div class=\"container-fluid\"><div class=\"ibox \"><div class=\"ibox-content text-center\"><h2><i class=\"glyphicon glyphicon-info-sign\"></i>{{message}}</h2></div></div></div>";
    var PAGE_SIZE = 10;//分页，每页10条
    /**
     * Ajax二次封装
     * @type {{ajax, abort}}
     */
    var AjaxReq = window.AjaxReq = function () {
        var config = {
            type: "GET",
            cache: false,
            success: function () {

            },
            error: function (xhr, textStatus, errorThrown, callback) {
                if (window.isunloading) {
                    return;
                }
                var status = xhr.status;
                switch (status) {
                    case 400:
                        toastr.error("您访问的请求无效，请确认！");
                        break;
                    case 401:
                        toastr.error("您无权访问该资源！");
                        break;
                    case 403:
                        toastr.error("您被禁止访问该资源！");
                        break;
                    case 404:
                        toastr.warning("您访问的资源系统没有提供！");
                        break;
                    case 0:
                        if ("abort" === textStatus) {

                        } else if ("error" == textStatus) {
                            toastr.error("系统服务中断，请联系管理员！")
                        }
                        break;
                    default:
                        toastr.error("系统发生了不可预期的错误。错误码：" + status);
                        break;
                }

                if (typeof(callback) == "function") {
                    callback(xhr, textStatus, errorThrown);
                }
            }
        };
        return {
            ajax: function (options) {
                var method_name = "";
                var type = "";
                if (!options.type) {
                    options.type = "GET";
                }
                switch (options.type.toUpperCase()) {
                    case "GET":
                        method_name = "GET";
                        type = "GET";
                        break;
                    case "POST":
                        method_name = "POST";
                        type = "POST";
                        break;
                    case "DELETE":
                        method_name = "DELETE";
                        type = "POST";
                        break;
                    case "PUT":
                        method_name = "PUT";
                        type = "POST";
                        break;
                    default:
                        method_name = "GET";
                        type = "GET";
                        break;
                }
                var option = $.extend({}, config, options || {});
                return $.ajax(option);
            },
            /**
             * 中断ajax执行
             * @param xhr
             */
            abort: function (xhr) {
                if (xhr && xhr.readyState != 4) {
                    xhr.abort();
                }
            }
        }
    }();
    /**
     * 分页插件
     */
    var Page = window.Page = function () {
        var config = {
            bootstrapMajorVersion: 3,
            currentPage: 1,
            numberOfPages: PAGE_SIZE,
            itemTexts: function (type, page, current) {
                switch (type) {
                    case "first":
                        return "首页";
                    case "prev":
                        return "上一页";
                    case "next":
                        return "下一页";
                    case "last":
                        return "末页";
                    case "page":
                        return page;
                }
            }
        };
        return {
            /**
             * 初始化
             */
            init: function (options, jqElem) {
                options = $.extend(options, config);
                jqElem.bootstrapPaginator(options);
            }
        }
    }();
    /**
     * 消息提示组件
     * @type {{success, warning, info, error}}
     */
    var Msg = window.Msg = function () {
        toastr.options = {
            "closeButton": true,//显示关闭按钮
            "debug": true,//启用debug
            "positionClass": "toast-top-center",//弹出的位置
            "showDuration": "300",//显示的时间
            "hideDuration": "1000",//消失的时间
            "timeOut": "1000",//停留的时间
            "extendedTimeOut": "1000",//控制时间
            "showEasing": "swing",//显示时的动画缓冲方式
            "hideEasing": "linear",//消失时的动画缓冲方式
            "showMethod": "fadeIn",//显示时的动画方式
            "hideMethod": "fadeOut",//消失时的动画方式
            iconClasses: {
                error: "toast-error",
                info: "toast-info",
                success: "toast-success",
                warning: "toast-warning"
            }
        };
        return {
            success: function (message, callback) {
                if (callback && typeof(callback) === "function") {
                    toastr.options.onHidden = callback;
                }
                toastr.success(message);
            },
            warning: function (message, callback) {
                if (callback && typeof(callback) === "function") {
                    toastr.options.onHidden = callback;
                }
                toastr.warning(message);
            },
            info: function (message, callback) {
                if (callback && typeof(callback) === "function") {
                    toastr.options.onHidden = callback;
                }
                toastr.info(message);
            },
            error: function (message, callback) {
                if (callback && typeof(callback) === "function") {
                    toastr.options.onHidden = callback;
                }
                toastr.error(message);
            }
        }
    }();
    /**
     * 弹框组件
     * @type {Window.Dialog}
     */
    var Dialog = window.Dialog = function () {
        var default_height = window.document.documentElement.clientHeight * 0.9 + "px";
        var default_width = window.document.documentElement.clientWidth * 0.9 + "px";
        var _interval;
        $(window).on("resize", function () {
            if (_interval) {
                clearTimeout(_interval);
            }
            _interval = setTimeout(function () {
                var default_height = window.document.documentElement.clientHeight * 0.9 + "px";
                var default_width = window.document.documentElement.clientWidth * 0.9 + "px";
                if (layer) {
                    layer.style(window.opendDialogIndex, {
                        width: default_width,
                        height: default_height
                    })
                }
            }, 500);

        });
        var config = {
            type: 2,
            title: false,
            closeBtn: false,
            shadeClose: true,
            shade: false,
            fixed: false,
            maxmin: false, //开启最大化最小化按钮
            area: [default_width, default_height],
            shift: 2
        };
        window.opendDialogIndex = -1;
        return {
            /**
             * 弹窗打开一个URL地址
             * @param url url地址
             * @param title 标题
             * @param options 属性
             */
            open: function (url, title, options) {
                var _options = {
                    type: 2,
                    closeBtn: true,
                    content: url,
                    maxmin: true,
                    title: title || false
                };
                options = $.extend(config, _options, options || {});
                window.opendDialogIndex = layer.open(options);
            },
            form: function (url, title, submitBtnName, submitBtnFunction, options) {
                var _options = {
                    type: 2,
                    closeBtn: true,
                    content: url,
                    maxmin: true,
                    title: title || false,
                    btn: [submitBtnName, "重置"],
                    yes: function (index, layero) {
                        var body = layer.getChildFrame('body', index);
                        submitBtnFunction(body, index, layero);
                    },
                    btn2: function (index, layero) {
                        var body = layer.getChildFrame('body', index);
                        var _form = body.find("form");
                        if (_form) {
                            _form[0].reset();
                            return;
                        }
                    }
                };
                options = $.extend(config, _options, options || {});
                var _index = layer.open(options);
                window.opendDialogIndex = _index;
            },
            /**
             * 步骤表单
             * @param title
             * @param steps JSON数组，每个JSON包含 name/content/type 三个属性
             *               name:步骤名称
             *               content:步骤内容/jQuery对象/URL
             *               type:html/jquery/url
             * @param callbacks
             * @param options
             */
            steps: function (title, steps, callbacks, options) {
                var getInnerBody = function (index) {
                    var _iframe = $(".step-content-" + index + " iframe");
                    var _body;
                    if (_iframe) {
                        _body = _iframe.contents().find("body");
                    } else {
                        _body = $(".step-content-" + index);
                    }
                    return _body;
                };
                if (steps) {
                    var _options = {
                        type: 5,
                        closeBtn: true,
                        steps: steps,
                        maxmin: true,
                        title: title || false,
                        success: function (layero, index) {
                            $("#layui-layer-wizard").steps({
                                labels: {
                                    cancel: "取 消",
                                    current: "当前步骤",
                                    finish: "办 理",
                                    next: "下一步",
                                    previous: "上一步",
                                    loading: "正在加载"
                                }
                                , onStepChanging: function (event, currentIndex, newIndex) {
                                    if (callbacks.onStepChanging && typeof callbacks.onStepChanging == "function") {
                                        var _body = getInnerBody(currentIndex);
                                        callbacks.onStepChanging(_body, currentIndex, newIndex);
                                    }
                                    return true;
                                },
                                onStepChanged: function (event, currentIndex, priorIndex) {
                                    if (callbacks.onStepChanged && typeof callbacks.onStepChanged == "function") {
                                        var _body = getInnerBody(currentIndex);
                                        callbacks.onStepChanged(_body, currentIndex, priorIndex);
                                    }
                                    return true;
                                }, onFinishing: function (event, currentIndex) {
                                    if (callbacks.onFinishing && typeof callbacks.onFinishing == "function") {
                                        var _body = getInnerBody(currentIndex);
                                        callbacks.onFinishing(_body, currentIndex);
                                    }
                                    layer.close(index);
                                    return true;
                                }, onFinished: function (event, currentIndex) {
                                    if (callbacks.onFinished && typeof callbacks.onFinished == "function") {
                                        var _body = getInnerBody(currentIndex);
                                        callbacks.onFinished(_body, currentIndex);
                                    }
                                    return true;
                                }, onCanceled: function () {
                                    layer.close(index);
                                }
                            });
                        }
                    };
                    options = $.extend(config, _options, options || {});
                    window.opendDialogIndex = layer.open(options);
                }
            },

            /**
             * 添加一个步骤
             * @param step 步骤JSON，{title:"",contentMode:"iframe/html",[contentUrl:"iframe的url",content:"html内容"]}
             */
            addStep: function (_step) {
                try {
                    $("#layui-layer-wizard").steps("getStep", 1)
                } catch (e) {
                    $("#layui-layer-wizard").steps("add", {
                        title: _step.title,
                        contentMode: _step.contentMode ? _step.contentMode : "html",
                        contentUrl: _step.contentUrl ? _step.contentUrl : "",
                        content: _step.content ? _step.content : ""
                    });
                }
            },

            /**
             * 删除一个step
             * @param index 被删除的step的索引位置
             */
            removeStep: function (index) {
                $("#layui-layer-wizard").steps("remove", index);
            },
            /**
             * 打开一段HTML或者Jquery元素
             * @param html
             */
            html: function (html, title, options) {
                var _options = {
                    type: 1,
                    closeBtn: true,
                    content: html,
                    maxmin: true,
                    title: title || false
                };
                options = $.extend(config, _options, options || {});
                this.opendDialogIndex = layer.open(options);
            }
            ,
            /**
             * 弹框，并通过tab页展示
             * @param tabs 数组，格式例如:[{title:"TAB1",content:"123"},{title:"TAB2",content:"http://www.baidu.com"}]
             * @param width 弹框宽度
             * @param height 弹框高度
             */
            tab: function (tabs, width, height) {
                if (!width) {
                    width = default_width;
                }
                if (!height) {
                    height = default_height;
                }
                var area = [width, height];
                this.opendDialogIndex = layer.tab({
                    area: area,
                    tab: tabs,
                    maxmin: true,
                    closeBtn: true
                });
            }
            ,
            alert: function (message, callback) {
                if (callback && typeof callback == "function") {
                    layer.alert(message, callback);
                } else {
                    layer.alert(message);
                }

            }
            ,
            confirm: function (message, yesName, yesFunction, noName, noFunction) {
                layer.confirm(message, [yesName, noName], yesFunction, noFunction);
            }
            ,
            /**
             * 显示Loading层，并返回弹出层对象，用于关闭
             * @returns {*}
             */
            loading: function () {
                return layer.load(2);
            }
            ,
            /**
             * 关闭loading弹出层
             * @param index
             */
            close: function (index) {
                if (index) {
                    layer.close(index);
                } else {
                    layer.closeAll();
                }

            }
            ,
        }
    }();
    return {
        noData: function (message) {
            return NO_DATA_HTML.replace("{{message}}", message);
        },
        loading: function (jqObject) {
            jqObject.html(LOADING_HTML);
        },
        errorData: function (message) {
            return ERROR_DATA_HTML.replace("{{message}}", message);
        },
        fullscreen: function (element) {
            if (element.requestFullscreen) {
                element.requestFullscreen();
            } else if (element.mozRequestFullScreen) {
                element.mozRequestFullScreen();
            } else if (element.msRequestFullscreen) {
                element.msRequestFullscreen();
            } else if (element.webkitRequestFullscreen) {
                element.webkitRequestFullScreen();
            }
        },
        exitFullscreen: function () {
            if (document.exitFullscreen) {
                document.exitFullscreen();
            } else if (document.msExistFullscreen) {
                document.msExistFullscreen();
            } else if (document.mozCancelFullScreen) {
                document.mozCancelFullScreen();
            } else if (document.webkitExitFullscreen) {
                document.webkitExitFullscreen();
            }
        }
    }
})(jQuery, window);

/**
 * 二次封装的ajax请求方法
 * @param options
 * @returns {*}
 * @constructor
 */
function ajaxRequest(options) {
    return AjaxReq.ajax(options);
}
;ajaxRequest.abort = function (xhr) {
    if (xhr && xhr.readyState != 4) {
        xhr.abort();
    }
}
/**
 * 系统登陆相关脚本
 * @type {{login, loginSuccessHandler}}
 */
;var login = (function ($) {
    var LOGIN_STATUS = {
        success: "<strong>登录成功！</strong> 系统登陆成功，正在跳转到首页。",
        error: "<strong>登录失败！</strong> 请检查用户名密码是否正确。"
    };

    return {
        /**
         * 用户登录
         */
        login: function () {
            var username = $("#username").val();
            var password = $("#password").val();
            $("#login-button").attr("disabled", "disabled").text("登录中...");
            ajaxRequest({
                url: $ctx + "/auth/authenticate",
                type: "POST",
                data: {username: username, password: password},
                success: function (data, status) {
                    $("#login-alert .content").html(LOGIN_STATUS[status]);
                    $("#login-alert").removeClass("alert-danger").addClass("alert-success").removeClass("hidden");
                    login.loginSuccessHandler();
                },
                error: function (xhr, status, headers, config) {
                    $("#login-alert .content").html(LOGIN_STATUS[status]);
                    $("#login-alert").removeClass("hidden").removeClass("alert-success").addClass("alert-danger");
                    $("#login-button").removeAttr("disabled").text("登 录");
                }
            });
        },
        loginSuccessHandler: function () {
            location.href = $ctx + "/index";
        }
    }
})(jQuery);

/**
 * 模型管理相关脚本
 */
var model = (function ($) {
    var deployed = 0;
    return {
        /**
         * 获取模型列表
         * @param deployed 是否部署
         */
        list: function (deployed) {
            global.loading($("#model-datas"));
            if (!deployed) {
                deployed = 0;
            }
            ajaxRequest({
                url: $ctx + "/flow/models/list?deployed=" + deployed,
                dataType: "json",
                success: function (data) {
                    model.listRender(data);
                }
            });
        },
        listRender: function (json) {
            var html = template("model-datas-tmpl", {
                "models": json
            });
            $("#model-datas").html(html);
        },
        create: function () {
            Dialog.form($ctx + "/flow/models/create", "新增模型", "创建", function (body) {
                var form = body.find("form");
                if (form.valid()) {
                    var params = form.serialize();
                    ajaxRequest({
                        url: $ctx + "/flow/models/create",
                        data: params,
                        method: "POST",
                        success: function (data) {
                            Dialog.close();
                            console.log(data);
                            var data = data.data;
                            location.href = $ctx + "/activiti/editor/#/editor/" + data.id;
                        }
                    })
                } else {
                    return;
                }
            })
        },
        upload: function () {
            Dialog.open($ctx + "/flow/models/upload", "导入模型");
        },
        /**
         * 根据模型ID部署模型
         * @param modelId
         */
        deployById: function (modelId) {
            ajaxRequest({
                url: $ctx + "/flow/models/" + modelId,
                method: "PUT",
                success: function (data) {
                    Msg.success("模型部署成功！", function () {
                        model.list();
                    });
                }
            })
        },
        /**
         * 撤销模型部署
         * @param definitionId
         */
        revoke: function (definitionId) {
            ajaxRequest({
                url: $ctx + "/flow/models/" + definitionId,
                method: "DELETE",
                success: function () {
                    Msg.success("撤销成功！", function () {
                        model.list();
                    });
                }
            })
        },
        delete: function (modelId) {
            Dialog.confirm("确定删除该模型吗？", "删除", function () {
                ajaxRequest({
                    url: $ctx + "/rest/models/" + modelId,
                    method: "DELETE",
                    success: function () {
                        layer.close(layer.index);
                        Msg.success("删除成功", function () {
                            model.list();
                        })
                    }
                })
            }, "取消");
        },
        /**
         * 如果启动事件有表单，则弹框展示表单。
         * 如果没有表单，则直接发起
         *
         * @param definitionId 流程定义标识
         * @param businessKey 业务ID
         */
        start: function (definitionKey, businessKey) {
            ajaxRequest({
                // 先判断该流程定义是否有发起表单，如果有则获取表单标识，然后根据表单标识跳转到表单页面
                // 同时获取下一步办理人，如果是需要选择的，则展示步骤
                url: $ctx + "/flow/api/forms/start/" + definitionKey,
                success: function (data) {
                    if (data) {
                        data = data.data;
                    }
                    if (data && data.formKey) {//如果有，则跳转到表单页面
                        var formUrl = $ctx + "/flow/forms/" + data.formKey + "?definitionKey=" + definitionKey;
                        forms.open(formUrl, data.nextSelectAssignee, "start", definitionKey, null, businessKey);
                    } else {//没有表单
                        Msg.error("发起流程缺少业务信息，请确认！");
                        return false;
                    }
                }
            });
        },
        /**
         * 提交发起表单
         * @param definitionId 流程定义ID
         * @param formId form元素ID
         */
        submit: function (definitionId, formId) {
            var $form = $("#" + formId);
            forms.submitStartForm(definitionId, $form.serialize(), 1);
        }
    }
})(jQuery);

/**
 * 表单操作相关类
 * @type {{submitStartForm, submitTaskForm}}
 */
var forms = (function ($) {
    return {
        /**
         * 启动流程时提交表单信息
         * @param definitionKey 流程定义标识
         * @param jqFormObject
         * @param businessKey
         */
        submitStartForm: function (definitionKey, params, businessKey) {
            if (!businessKey) {
                businessKey = new Date().getMilliseconds();
            }
            ajaxRequest({
                url: $ctx + "/flow/instances/start/" + definitionKey,
                data: params + "&businessKey=" + businessKey,
                method: "POST",
                success: function () {
                    Dialog.close();
                    Msg.success("业务申请成功", function () {
                        location.reload();
                    });
                }
            })
        },
        /**
         * 办理任务时提交表单信息
         * @param taskId
         * @param jqFormObject
         */
        submitTaskForm: function (taskId, params) {
            ajaxRequest({
                url: $ctx + "/flow/tasks/" + taskId,
                data: params ? params : "",
                method: "POST",
                success: function () {
                    Dialog.close();
                    Msg.success("业务办理成功", function () {
                        location.reload();
                    });
                }
            })
        },
        /**
         * 弹框展示处理单
         * @param url 表单获取地址
         * @param nextSelectAssignee 下一步办理人选择项
         * @param startOrTask start:开始事件；task:用户任务
         * @param definitionKeyOrTaskId 如果是开始事件，填写流程定义标识。如果是任务，则输入任务ID
         * @param isNextGateway 判断下一个节点是否是网关。如果是的话，默认弹出的表单是步骤表单，只是只展示第一个表单。防止如果根据网关需要展示选择用户页面，但是却不是步骤表单而报错的问题。
         * @param businessKey 业务标识
         */
        open: function (url, nextSelectAssignee, startOrTask, definitionKeyOrTaskId, isNextGateway, businessKey) {
            var formVariables = {};
            var title = startOrTask == "start" ? "发起流程" : "业务办理";
            if (nextSelectAssignee) {//需要选择办理用户
                Dialog.steps(title, [{
                    name: "业务单",
                    content: url,
                    type: "url"
                }, {
                    name: "选择办理人员",
                    content: $ctx + "/flow/forms/assignee/page?selectType=" + nextSelectAssignee,
                    type: "url"
                }], {
                    onStepChanging: function ($body, stepIndex, nextIndex) {
                        if ($body.find("form").size() == 0) {
                            $body = $("#layui-layer-wizard-p-" + stepIndex).find("iframe").contents().find("body");
                        }
                        formVariables["step" + stepIndex] = $body.find("form").serialize();
                    },
                    onFinishing: function ($body, stepIndex) {
                        if ($body.find("form").size() == 0) {
                            $body = $("#layui-layer-wizard-p-" + stepIndex).find("iframe").contents().find("body");
                        }
                        formVariables["step" + stepIndex] = $body.find("form").serialize();
                    },
                    onFinished: function ($body, stepIndex) {
                        var _formVariables = [];
                        $.each(formVariables, function (i, v) {
                            _formVariables.push(v);
                        });
                        var params = _formVariables.join("&");
                        if (startOrTask == "start") {
                            forms.submitStartForm(definitionKeyOrTaskId, params, businessKey);
                        } else {
                            forms.submitTaskForm(definitionKeyOrTaskId, params);
                        }
                    }
                }, {id: "flowDialog"});
            } else if (isNextGateway) {
                Dialog.steps(title, [{
                    name: "业务单",
                    content: url,
                    type: "url"
                }], {
                    onStepChanging: function ($body, stepIndex, nextIndex) {
                        if ($body.find("form").size() == 0) {
                            $body = $("#layui-layer-wizard-p-" + stepIndex).find("iframe").contents().find("body");
                        }
                        formVariables["step" + stepIndex] = $body.find("form").serialize();
                    },
                    onFinishing: function ($body, stepIndex) {
                        if ($body.find("form").size() == 0) {
                            $body = $("#layui-layer-wizard-p-" + stepIndex).find("iframe").contents().find("body");
                        }
                        formVariables["step" + stepIndex] = $body.find("form").serialize();
                    },
                    onFinished: function ($body, stepIndex) {
                        var _formVariables = [];
                        $.each(formVariables, function (i, v) {
                            _formVariables.push(v);
                        });
                        var params = _formVariables.join("&");
                        if (startOrTask == "start") {
                            forms.submitStartForm(definitionKeyOrTaskId, params, businessKey);
                        } else {
                            forms.submitTaskForm(definitionKeyOrTaskId, params);
                        }
                    }
                }, {id: "flowDialog"});
            } else {
                Dialog.form(url, title, "提交流程", function (body, index) {
                    var $form = body.find("form");
                    var params = $form.serialize();
                    if (startOrTask == "start") {
                        forms.submitStartForm(definitionKeyOrTaskId, params, businessKey);
                    } else {
                        forms.submitTaskForm(definitionKeyOrTaskId, params);
                    }
                }, {id: "flowDialog"});
            }
        },
        /**
         * 获取下一节点的办理用户。如果下一节点的办理用户是需要选择，则添加选择用户的tab；否则删除该tab。
         * @param taskId
         * @param nextStep
         */
        getNextAssignee: function (taskId, conditionJson) {
            if (conditionJson && typeof conditionJson == "object") {
                conditionJson = JSON.stringify(conditionJson);
            }
            ajaxRequest({
                url: $ctx + "/flow/api/assignee",
                data: "taskId=" + taskId + (conditionJson ? ("&condition=" + encodeURIComponent(conditionJson)) : ""),
                method: "GET",
                success: function (data) {
                    data = data.data;
                    if (data.valueType == "Select") {//需要选择用户
                        var url = $ctx + "/flow/forms/assignee/page?selectType=" + data.value;
                        parent.addStep({
                            title: "选择办理人员",
                            "contentMode": "iframe",
                            "contentUrl": url
                        })
                    } else {
                        parent.deleteStep(1);
                    }
                }
            });
        }
    }
})(jQuery);
/**
 * 任务管理模块
 */
var task = (function ($) {
    return {
        /**
         * 弹出任务办理页面,先获取任务办理的页面标识
         * @param taskId
         */
        todoTask: function (taskId) {
            ajaxRequest({
                url: $ctx + "/flow/api/forms/task/" + taskId,
                success: function (data) {
                    if (data) {
                        data = data.data;
                    }
                    if (data && data.formKey) {
                        var formKey = data.formKey;
                        var nextSelectAssignee = data.nextSelectAssignee;
                        var formUrl = $ctx + "/flow/forms/" + formKey + "?taskId=" + taskId;
                        forms.open(formUrl, nextSelectAssignee, "task", taskId, data.nextNodeIsGateway, null);
                    } else {//没有办理页面，直接处理完成
                        forms.submitTaskForm(taskId, null);
                    }
                }
            })
        },
        /**
         * 任务详情
         * @param taskId
         */
        detail: function (taskId, isProcessInstanceId) {
            var varname = isProcessInstanceId ? "instanceId" : "taskId";
            Dialog.tab([
                    {
                        title: "办理历史",
                        content: $ctx + "/flow/instances/history/page?" + varname + "=" + taskId,
                        type: 2
                    },
                    {
                        title: "业务详情",
                        content: $ctx + "/flow/forms/startFormDetail?taskId=" + taskId,
                        type: 2
                    }
                ]
            );
        },
        /**
         * 任务办理，不需要填写表单，直接办理
         * @param taskId
         */
        submit: function (taskId, formId) {
            var form = $("#" + formId);
            forms.submitTaskForm(taskId, form.serialize());
        },
        delegate: function (taskId) {
            var formUrl = $ctx + "/flow/forms/assignee/delegate?taskId=" + taskId;
            Dialog.form(formUrl, "委托他人办理", "提交", function (body, index) {
                var assignee = body.find("form").find("select option:selected").val();
                if (!assignee) {
                    Msg.error("请选择委托人")
                }
                ajaxRequest({
                    url: $ctx + "/flow/api/tasks/" + taskId + "/delegate/" + assignee,
                    method: "POST",
                    success: function (data) {
                        data = data.data;
                        if (data) {
                            Msg.success("任务委托成功！", function () {
                                Dialog.close();
                                location.reload();
                            });
                        } else {
                            Msg.error("任务委托失败！");
                        }
                    }
                })
            });
        }
    }
})(jQuery);

/**
 * 流程实例相关操作类
 */
var instance = (function ($) {
    return {
        /**
         * 删除流程实例
         * @param instanceId 流程实例ID
         */
        delete: function (instanceId) {
            Dialog.confirm("确定删除该流程实例吗？", "确定", function () {
                ajaxRequest({
                    url: $ctx + "/flow/api/instances/" + instanceId,
                    method: "DELETE",
                    success: function (data) {
                        Msg.success("流程实例删除成功", function () {
                            location.reload();
                            Dialog.close();
                        })
                    }
                })
            }, "取消", function () {
                Dialog.close();
            })
        },
        /**
         * 获取流程详情
         * @param instanceId
         */
        detail: function (instanceId) {
            Dialog.tab([
                    {
                        title: "办理历史",
                        content: $ctx + "/flow/instances/history/page?instanceId=" + instanceId,
                        type: 2
                    },
                    {
                        title: "业务详情",
                        content: $ctx + "/flow/forms/startFormDetail?instanceId=" + instanceId,
                        type: 2
                    }
                ]
            );
        },
        /**
         * 挂起流程
         * @param instanceId
         */
        suspend: function (instanceId) {
            Dialog.confirm("确定挂起该流程吗？", "确定", function () {
                ajaxRequest({
                    url: $ctx + "/flow/api/instances/" + instanceId + "/suspend",
                    method: "POST",
                    success: function (data) {
                        var data = data.data;
                        if (data) {
                            Msg.success("流程挂起成功", function () {
                                location.reload();
                            });
                        } else {
                            Msg.success("流程挂起失败");
                        }
                    }
                })
            }, "取消", function () {

            });

        },
        /**
         * 激活流程
         * @param instanceId
         */
        active: function (instanceId) {
            ajaxRequest({
                url: $ctx + "/flow/api/instances/" + instanceId + "/active",
                method: "POST",
                success: function (data) {
                    var data = data.data;
                    if (data) {
                        Msg.success("流程激活成功", function () {
                            location.reload();
                        });
                    } else {
                        Msg.success("流程激活失败");
                    }
                }
            })
        },
        /**
         * 获取列表
         * @param status
         */
        list: function (status) {
            if (!status) {
                $table.bootstrapTable("refresh", "");
            } else {
                $table.bootstrapTable("refresh", {query: {status: status}});
            }
        }
    }
})(jQuery);

/**
 * 添加步骤
 * @param step
 */
function addStep(step) {
    Dialog.addStep(step);
}

/**
 * 删除步骤
 */
function deleteStep(index) {
    Dialog.removeStep(index);
}

/**
 * 用于bootstrap datables组件的data-formatter通用函数
 * @type {{showUser}}
 */
var datatablesfn = (function ($) {
    return {
        /**
         * 展示 FlowProfile封装的结果中的用户名
         * @param profile
         * @returns {*}
         */
        showUser: function (profile) {
            var html = profile ? profile.userName : "";
            return html;
        },
        setFontWeight: function (data) {
            var html = "<h3>" + data + "</h3>";
            return html;
        },
        showStatus: function (status) {
            var html = "<span class='label " + CONSTANTS.FLOW_STATUS[status]['label-class'] + "'>" + CONSTANTS.FLOW_STATUS[status]['label-text'] + "</span>";
            return html;
        }
    }
})(jQuery);